package com.qingyun.user.interceptor;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.qingyun.model.user.pojos.User;
import com.qingyun.user.service.UserService;
import org.apache.catalina.Manager;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import utils.common.RedisConstants;
import utils.thread.AppThreadLocalUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static utils.common.RedisConstants.LOGIN_USER_KEY;


@Component
public class TokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    private UserService userService;

    //通过构造注入
    public TokenInterceptor(StringRedisTemplate stringRedisTemplate,UserService userService){
        this.stringRedisTemplate=stringRedisTemplate;
        this.userService=userService;

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "86400");
        response.setHeader("Access-Control-Allow-Headers", "*");

        // 如果是OPTIONS则结束请求
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            response.setStatus(HttpStatus.NO_CONTENT.value());
            return true;
        }
        //1.获取请求头的token
        String token = request.getHeader("Authorization");//前端页面定义的请求头

        if (StrUtil.isBlank(token)){
            //不存在拦截,返回401状态码
            response.setStatus(401);
            return false;
        }

        //2.基于token获取redis中的用户
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(LOGIN_USER_KEY + token);
        if (userMap == null || userMap.size() <= 0){
            //不存在拦截,返回401状态码
            response.setStatus(401);
            return false;
        }
        //5.将查询到的Hash数据转为UserDTO对象
        //将map中的数据自动填充到对象中，false是忽视错误，有异常直接往外抛就行了
        User user = BeanUtil.fillBeanWithMap(userMap, new User(), false);
//        User one = userService.query().eq("id", user.getId()).one();

        //6.存在，保存用户信息到TreadLocal中
        AppThreadLocalUtil.setUser(user);
        //7.刷新token的有效期
        stringRedisTemplate.expire(LOGIN_USER_KEY + token,30, TimeUnit.MINUTES);
        //8.放行
        return true;
    }
}
